package com.alex.controller.test;

import com.alex.pojo.User;
import com.alex.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.validation.Valid;

@Controller
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("/converter")
    public String t(@RequestParam("user") User user, Model model) {
        System.out.println(user);
        model.addAttribute("user", user);
        return "test/converter";
    }

    @ModelAttribute
    public void getUser(Model model) {
        User user = userService.getById(1);
        model.addAttribute("muser", user);
    }

    @RequestMapping("/test/user")
    public String postUser(@Valid User user, Model model, BindingResult bindingResult) {
        System.out.println("表单数据: " + user);
        System.out.println("bindingResult: " + bindingResult.getErrorCount());
        model.addAttribute("user", user);
        System.out.println("=====================================================");
        if (bindingResult.getErrorCount() > 0) {
            return "test/index";
        }
        return "test/user";
    }
}
